<template>
  <div class="version-history">
    <div class="version-header">
      <h3>版本历史</h3>
      <button @click="toggleHistory" class="toggle-btn">
        {{ showHistory ? '隐藏' : '显示' }}历史
      </button>
    </div>
    
    <div v-if="showHistory && versions.length > 0" class="version-list">
      <div 
        v-for="version in versions" 
        :key="version.id"
        class="version-item"
        :class="{ active: selectedVersionId === version.id }"
      >
        <div class="version-info">
          <span class="version-number">v{{ version.version_number }}</span>
          <span class="version-date">{{ formatDate(version.created_at) }}</span>
          <span class="version-title">{{ version.name }}</span>
          <span v-if="version.change_summary" class="version-summary">
            {{ version.change_summary }}
          </span>
          <span class="version-size">{{ formatSize(version.content_length) }}</span>
        </div>
        
        <div class="version-actions">
          <button 
            @click="viewVersion(version.id)"
            class="view-btn"
            :disabled="selectedVersionId === version.id"
          >
            查看
          </button>
          <button 
            @click="restoreVersion(version.id, version.version_number)"
            class="restore-btn"
          >
            恢复
          </button>
        </div>
      </div>
    </div>
    
    <div v-else-if="showHistory" class="no-versions">
      暂无版本历史
    </div>
    
    <!-- 版本对比模态框 -->
    <div v-if="showVersionModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h4>版本 v{{ selectedVersion?.version_number }} - {{ selectedVersion?.name }}</h4>
          <button @click="closeModal" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <div class="version-meta">
            <p><strong>创建时间:</strong> {{ formatDate(selectedVersion?.created_at) }}</p>
            <p v-if="selectedVersion?.change_summary">
              <strong>修改说明:</strong> {{ selectedVersion.change_summary }}
            </p>
          </div>
          <div class="version-content">
            <h5>内容预览:</h5>
            <pre>{{ selectedVersion?.content }}</pre>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="restoreVersion(selectedVersion?.id, selectedVersion?.version_number)" 
                  class="restore-btn">
            恢复到此版本
          </button>
          <button @click="closeModal" class="cancel-btn">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'

const props = defineProps({
  noteId: {
    type: [String, Number],
    required: true
  }
})

const emit = defineEmits(['version-restored'])

const versions = ref([])
const showHistory = ref(false)
const selectedVersionId = ref(null)
const showVersionModal = ref(false)
const selectedVersion = ref(null)

// 获取版本历史
const fetchVersions = async () => {
  try {
    const response = await fetch(`/api/notes/getNoteVersions?noteId=${props.noteId}`)
    const data = await response.json()
    if (data.success) {
      versions.value = data.versions
    }
  } catch (error) {
    console.error('获取版本历史失败:', error)
  }
}

// 查看特定版本
const viewVersion = async (versionId) => {
  try {
    const response = await fetch(`/api/notes/getNoteVersionContent?noteId=${props.noteId}&versionId=${versionId}`)
    const data = await response.json()
    if (data.success) {
      selectedVersion.value = data.version
      selectedVersionId.value = versionId
      showVersionModal.value = true
    }
  } catch (error) {
    console.error('获取版本内容失败:', error)
  }
}

// 恢复到特定版本
const restoreVersion = async (versionId, versionNumber) => {
  if (!confirm(`确定要恢复到版本 ${versionNumber} 吗？当前内容将被保存为新版本。`)) {
    return
  }
  
  try {
    const response = await fetch('/api/notes/restoreNoteVersion', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        noteId: props.noteId,
        versionId: versionId
      })
    })
    
    const data = await response.json()
    if (data.success) {
      alert(data.message)
      emit('version-restored')
      closeModal()
      await fetchVersions() // 刷新版本列表
    }
  } catch (error) {
    console.error('恢复版本失败:', error)
    alert('恢复版本失败')
  }
}

// 切换历史显示
const toggleHistory = () => {
  showHistory.value = !showHistory.value
  if (showHistory.value && versions.value.length === 0) {
    fetchVersions()
  }
}

// 关闭模态框
const closeModal = () => {
  showVersionModal.value = false
  selectedVersion.value = null
}

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 格式化文件大小
const formatSize = (bytes) => {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}

// 监听noteId变化
watch(() => props.noteId, () => {
  if (showHistory.value) {
    fetchVersions()
  }
})

onMounted(() => {
  if (showHistory.value) {
    fetchVersions()
  }
})
</script>

<style scoped>
.version-history {
  margin-top: 20px;
  border: 1px solid #e1e5e9;
  border-radius: 8px;
  overflow: hidden;
}

.version-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e1e5e9;
}

.version-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.toggle-btn {
  padding: 6px 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.toggle-btn:hover {
  background-color: #0056b3;
}

.version-list {
  max-height: 300px;
  overflow-y: auto;
}

.version-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e1e5e9;
}

.version-item:hover {
  background-color: #f8f9fa;
}

.version-item.active {
  background-color: #e3f2fd;
}

.version-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.version-number {
  background-color: #6c757d;
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 11px;
  font-weight: bold;
}

.version-date {
  color: #6c757d;
  font-size: 12px;
}

.version-title {
  font-weight: 500;
  color: #333;
}

.version-summary {
  color: #666;
  font-style: italic;
  font-size: 12px;
}

.version-size {
  color: #6c757d;
  font-size: 11px;
}

.version-actions {
  display: flex;
  gap: 8px;
}

.view-btn, .restore-btn {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 3px;
  cursor: pointer;
  font-size: 11px;
}

.view-btn {
  background-color: #f8f9fa;
  color: #333;
}

.view-btn:hover:not(:disabled) {
  background-color: #e9ecef;
}

.view-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.restore-btn {
  background-color: #28a745;
  color: white;
  border-color: #28a745;
}

.restore-btn:hover {
  background-color: #218838;
}

.no-versions {
  padding: 20px;
  text-align: center;
  color: #6c757d;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e1e5e9;
}

.modal-header h4 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6c757d;
}

.modal-body {
  padding: 16px;
  overflow-y: auto;
  flex: 1;
}

.version-meta p {
  margin: 8px 0;
  color: #666;
}

.version-content h5 {
  margin: 16px 0 8px 0;
  color: #333;
}

.version-content pre {
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
  max-height: 300px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px;
  border-top: 1px solid #e1e5e9;
}

.cancel-btn {
  padding: 8px 16px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #545b62;
}
</style>
